package Work.com;

import java.util.Scanner;

public class Exam03 {
    //编写一个函数，接受一个字符串数组作为输入，返回这些字符串的最长公共前缀。
    public static String compereString(String[] str){
        if (str == null || str.length == 0){
            return null;
        }
        String index = str[0];
        for (int i = 1; i < str.length ; i++) {
            while (str[i].indexOf(index) != 0){
                index = index.substring(0,index.length() - 1);
                if (index.isEmpty() ){
                    return null;
                }
            }
        }
        return index;
    }
    public static String longPrefix(String[] strings) {
        String str = strings[0];
        for (int i = 1; i < strings.length; i++) {
            if (strings[i].length() < str.length()) {
                str = strings[i];
            }
        }
        // 用最短的和后面的每一个比较
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            for (int j = 0; j < strings.length; j++) {
                if (strings[j].charAt(i) != c) {
                    return sb.toString();
                }
            }
            sb.append(c);
        }
        return sb.toString();
    }


    public static String longPrefix2(String[] strings) {
        String str = strings[0];
        for (int i = 1; i < strings.length; i++) {
            int j = 0;
            while (j < strings.length && j < strings[i].length()) {
                if (str.charAt(j) != strings[i].charAt(j)) {
                    break;
                }
                j++;
            }
            if (j == 0) {
                return "";
            }
            str = str.substring(0, j);
        }
        return str;
    }

    public static String longPrefix3(String[] strings) {
        String str = strings[0];
        // qwe we contains true indexOf = 1  0
        for (int i = 1; i < strings.length; i++) {
            while (strings[i].indexOf(str) != 0) {
                str = str.substring(0, str.length() - 1);
                if (str.isEmpty()) {
                    return str;
                }
            }
        }
        return str;
    }

    public static void main(String[] args) {
//        Scanner sc = new Scanner(System.in);
//        System.out.println("请输入字符串数组：");
//        String[] strings = new String[]{sc.next()};
        String[] str = {"apple","appetite","applicable"};
        String[] str1 = {"dag","cat","cow"};
        System.out.println("字符串的最长公共前缀为：" + compereString(str));
    }

//    public static String[] Ste(String... strings){
//        Scanner sc = new Scanner(System.in);
//        for (int i = 0; i < 2; i++) {
//            strings[i] = sc.next();
//        }
//        return strings;
//    }
}
